package com.heima.user.service.impl;

import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.UserRelationService;
import com.heima.user.thread.AppThreadLocalUtil;
import io.swagger.models.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author daxin
 * @date 2022/7/28 10:18
 */
@Service
@Slf4j
public class UserRelationServiceImpl implements UserRelationService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult UserFollow(UserRelationDto dto) {

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Integer userId = user.getId();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        Integer authorId = dto.getAuthorId();
        Short operation = dto.getOperation();

        if (0 == operation) {

            //添加关注
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION, userId.toString(), System.currentTimeMillis());
            //添加粉丝
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION, authorId.toString(), System.currentTimeMillis());

        } else if (1 == operation) {
            //取消关注
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION, userId.toString(), System.currentTimeMillis());
            //取消粉丝
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION, authorId.toString(), System.currentTimeMillis());
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
